package api

import (
	"context"
	"fmt"
	"github.com/kadycui/fiber-ci/pkg/cache"
	"github.com/kadycui/fiber-ci/pkg/database"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"github.com/kadycui/fiber-ci/model"
	"github.com/kadycui/fiber-ci/serialize"
)

// GetSuById is a function to get a Su by ID
// @Summary 通过ID获取一个Su详情
// @Description 通过ID一个Su详情
// @Tags Su
// @Accept json
// @Produce json
// @Param id path int true "Su ID"
// @Success 200 {object} serialize.ResponseHTTP{data=[]model.Su}
// @Failure 404 {object} serialize.ResponseHTTP{}
// @Failure 503 {object} serialize.ResponseHTTP{}
// @Router /v1/su/{id} [get]
// @Security ApiKeyAuth
func GetSuById(c *fiber.Ctx) error {
	r := c.Request()
	fmt.Println(r)
	h := c.GetRespHeaders()
	fmt.Println(h)
	id := c.Params("id")
	db := database.DB
	rdb := cache.RDB

	su := new(model.Su)
	if err := db.First(&su, id).Error; err != nil {
		switch err.Error() {
		case "record not found":
			return c.Status(http.StatusNotFound).JSON(serialize.ResponseHTTP{
				Success: false,
				Message: fmt.Sprintf("Lu with ID %v not found.", id),
				Data:    nil,
			})
		default:
			return c.Status(http.StatusServiceUnavailable).JSON(serialize.ResponseHTTP{
				Success: false,
				Message: err.Error(),
				Data:    nil,
			})

		}
	}

	cs := su.GetCacheSu()

	// 存储到 Redis
	err := serialize.SetCache(context.Background(), rdb, id, "su", cs)
	if err != nil {
		panic(err)
	}

	return c.JSON(serialize.ResponseHTTP{
		Success: true,
		Message: "Success get Lu by ID.",
		Data:    *su,
	})

}
